package cn.demo.client.api;


import cn.demo.client.domain.dto.OrderCreateDto;
import cn.demo.client.domain.dto.OrderQueryDto;
import cn.demo.common.annotation.Log;
import cn.demo.common.core.controller.BaseController;
import cn.demo.common.core.domain.R;
import cn.demo.common.core.page.PageQuery;
import cn.demo.common.core.page.PageR;
import cn.demo.common.enums.BusinessType;
import cn.demo.common.exception.ServiceException;
import cn.demo.common.utils.DateUtils;
import cn.demo.common.utils.SecurityUtils;
import cn.demo.pm.domain.PmIntegralBill;
import cn.demo.pm.domain.PmSignRecord;
import cn.demo.pm.domain.PmStoreGoods;
import cn.demo.pm.domain.PmStoreOrder;
import cn.demo.pm.service.IPmIntegralBillService;
import cn.demo.pm.service.IPmSignRecordService;
import cn.demo.pm.service.IPmStoreGoodsService;
import cn.demo.pm.service.IPmStoreOrderService;
import cn.demo.sys.service.ISysConfigService;
import cn.demo.um.domain.UmClientUser;
import cn.demo.um.service.IUmClientUserService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author xtjun
 * @description 积分api
 * @date 2024/06/04
 */
@Tag(name = "积分api")
@RestController
@RequestMapping("/api/pm")
public class PmApi extends BaseController {

    @Resource
    private IPmSignRecordService pmSignRecordService;
    @Resource
    private IPmIntegralBillService pmIntegralBillService;
    @Resource
    private IUmClientUserService umClientUserService;
    @Resource
    private IPmStoreGoodsService pmStoreGoodsService;
    @Resource
    private IPmStoreOrderService pmStoreOrderService;
    @Resource
    private ISysConfigService configService;
    @Operation(summary = "签到")
    @PutMapping("/sign")
    @Transactional
    public R sign() {

        long integral = Long.parseLong(configService.selectConfigByKey("sign_integral"));

        String userId = SecurityUtils.getUserId();
        String deptId = SecurityUtils.getDeptId();
        Date now = new Date();

        long count = pmSignRecordService.count(QueryWrapper.create().eq(PmSignRecord::getUserId, userId).between(PmSignRecord::getCreateTime, DateUtils.beginOfDay(now), DateUtils.endOfDay(now)));
        if (count > 0) {
            throw new ServiceException("今日已签到，请勿重复签到");
        }

        UmClientUser user = umClientUserService.getById(userId);
        user.setIntegral((null == user.getIntegral() ? 0 : user.getIntegral()) + integral);
        user.setIntegralTotal((null == user.getIntegralTotal() ? 0 : user.getIntegralTotal()) + integral);
        boolean b = umClientUserService.updateById(user);

        if (b) {
            PmSignRecord signRecord = new PmSignRecord();
            signRecord.setUserId(userId);
            signRecord.setIntegral(integral);
            signRecord.setDeptId(deptId);
            pmSignRecordService.insertPmSignRecord(signRecord);

            PmIntegralBill bill = new PmIntegralBill();
            bill.setUserId(userId);
            bill.setIntegral(integral);
            bill.setDeptId(deptId);
            bill.setBillName("签到赠送积分");
            bill.setLinkId(signRecord.getId());
            bill.setBillType(1);
            pmIntegralBillService.insertPmIntegralBill(bill);
        }

        return toAjax(b);
    }

    @Operation(summary = "查询积分签到记录列表")
    @GetMapping("/list")
    @Parameters({@Parameter(name = "startDate", description = "开始日期(yyyy-MM-dd)"), @Parameter(name = "endDate", description = "结束日期(yyyy-MM-dd)"),})
    public R<List<PmSignRecord>> list(String startDate, String endDate) {
        List<PmSignRecord> list = pmSignRecordService.list(QueryWrapper.create().eq(PmSignRecord::getUserId, getUserId()).between(PmSignRecord::getCreateTime, DateUtils.beginOfDay(startDate), DateUtils.endOfDay(endDate)).orderBy(PmSignRecord::getCreateTime, false));
        return R.ok(list);
    }

    @Operation(summary = "查询积分账单列表")
    @GetMapping("/integralBillList")
    public PageR<PmIntegralBill> integralBillList(PageQuery pageQuery) {
        PmIntegralBill param = new PmIntegralBill();
        param.setUserId(SecurityUtils.getUserId());
        pageQuery.setOrder("desc");
        pageQuery.setOrderByColumn("create_time");
        Page<PmIntegralBill> page = pmIntegralBillService.selectPmIntegralBillPage(param, pageQuery);
        return PageR.ok(page);
    }

    @Operation(summary = "查询积分商城产品列表")
    @GetMapping("/goodsList")
    public PageR<PmStoreGoods> goodsList(PmStoreGoods pmStoreGoods, PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryWrapper.create(pmStoreGoods, PmStoreGoods.operators)
                .eq(PmStoreGoods::getIsEnable, 1)
                .ge(PmStoreGoods::getQuantity, 1);
        Page<PmStoreGoods> page = pmStoreGoodsService.page(pageQuery.build(), queryWrapper);
        return PageR.ok(page);
    }

    @Operation(summary = "新增积分商城订单")
    @PostMapping("/addOrder")
    public R addOrder(@RequestBody @Validated OrderCreateDto dto) {
        if (dto.getGoodsNum() < 1){
            throw new ServiceException("数量至少为1");
        }
        return toAjax(pmStoreOrderService.addOrder(dto.toEntry()));
    }

    @Operation(summary = "查询我的商城订单")
    @GetMapping("/listOrder")
    public PageR<PmStoreOrder> listOrder(OrderQueryDto dto, PageQuery pageQuery) {
        PmStoreOrder order = dto.toEntry();
        order.setUserId(SecurityUtils.getUserId());
        Page<PmStoreOrder> page = pmStoreOrderService.selectPmStoreOrderPage(order, pageQuery);
        return PageR.ok(page);
    }

    @Operation(summary = "取消商城订单")
    @PutMapping("/cancelOrder/{id}")
    public R cancelOrder(@PathVariable String id) {
        PmStoreOrder order = pmStoreOrderService.getById(id);
        if (null == order){
            throw new ServiceException("订单不存在");
        }
        if (order.getOrderStatus() != 0){
            throw new ServiceException("当前状态不能取消");
        }
        order.setOrderStatus(3);
        return toAjax(pmStoreOrderService.updatePmStoreOrder(order));
    }

    @Operation(summary = "商城订单确认收货")
    @PutMapping("/confirmOrder/{id}")
    public R confirmOrder(@PathVariable String id) {
        PmStoreOrder order = pmStoreOrderService.getById(id);
        if (null == order){
            throw new ServiceException("订单不存在");
        }
        if (order.getOrderStatus() != 1){
            throw new ServiceException("当前状态不能确认收货");
        }
        order.setOrderStatus(3);
        return toAjax(pmStoreOrderService.updatePmStoreOrder(order));
    }
}
